import Env from '@/util/Env.js'
const baseUrl = Env.getDevBaseURL();
/*
token 是否添加token
headerState 是否需要开启表单提交数据
customHeader 自定义header头部
*/
const http = ({ url = '', param = {},token,headerState,customHeader, ...other } = {}) => {
  let timeStart = Date.now();
  let header = {
	  'Accept': 'application/json', //Accept代表发送端（客户端）希望接受的数据类型。
	  'content-type': 'application/json', //代表发送端（客户端|服务器）发送的实体数据的数据类型。
	  'X-Requested-With': 'XMLHttpRequest',
  }
  if(headerState){
  	  header = {
  		  'content-type': 'application/x-www-form-urlencoded',//form表单传值
  	  }
  }
  if(customHeader){ //自定义头部
  	header = customHeader
  }
  if(token){
	  // header['Authorization'] = uni.getStorageSync("token").replace("Bearer","Bearer ")
	  // header['Authorization'] = uni.getStorageSync("token") ? "Bearer "+ uni.getStorageSync("token"):''
	  header['X-Token'] = uni.getStorageSync("token") ? uni.getStorageSync("token"):''
  }
  return new Promise((resolve, reject) => {
    wx.request({
      timeout: 60000,// 超时时间
      url: getUrl(url),
      data: param,
	  header: header,
      ...other,
	  success (res) {
	  	// console.log('####### API success: ', res)
	  },
	  fail(error) {
	  	// console.error('####### API Response error: ', error)
	  	wx.hideLoading()
	  	wx.showToast({
	  		title: "网络连接超时/网络连接异常",
	  		icon: 'none',
	  		duration: 3000,
	  	})
	  },
      complete(res) {
        wx.hideLoading();
        // console.warn(`耗时${Date.now()} - timeStart`);
		// console.log('####### API complete: ', res)
        if(res.statusCode >= 200 && res.statusCode < 300){
          resolve(res.data);
		  if(res.data.code == 401){ //登录超时
			 uni.showModal({
			 	title: '提示',
			 	content: '登录超时，请重新登录！',
			 	showCancel: false,
			 	success: (res) => {
			 		uni.reLaunch({url:'/pages/index/login'})
			 		// uni.navigateTo({ url: '/pages/login/login' })
			 	}
			 })
		  }
        }else if(res.statusCode == 404){
			uni.showToast({title:'接口不存在,错误二维码!',icon: 'none',duration:2000});
		}else{
          reject(res);
        }
      }
    })
  })
}

const getUrl = (url) => {
  if(url.indexOf('://') == -1){
    url = baseUrl + url;
  }
  return url;
}

const get = (url, param = {},token = false,headerState = false,customHeader = false) => {
  return http({
    url,
    param,
	token,
	headerState,
	customHeader
  });
}

const post = (url, param = {},token = false,headerState = false,customHeader = false) => {
  return http({
    url,
    param,
	token,
	headerState,
	customHeader,
    method: 'post'
  });
}

const put = (url, param = {},token = false,headerState = false,customHeader = false) => {
  return http({
    url,
    param,
	token,
	customHeader,
    method: 'put'
  });
}

const del =  (url, param ={},token = false,headerState = false,customHeader = false) => {
  return http({
    url,
    param,
	token,
	customHeader,
    method: 'delete'
  });
}

module.exports = {
  baseUrl,
  get,
  post,
  put,
  del
}

// 例子
// this.$http.get('https://ccdcapi.alipay.com/validateAndCacheCardInfo.json',{
// 	_input_charset:'utf-8',
// 	cardNo:'6227003320240034988',
// 	cardBinCheck:true
// },false).then(result => {
// 	console.log(result.bank)
// }).catch(err => {
// 	uni.showToast({ title: err.msg, icon: 'none' });
// })